package luj.tool.jnproxyan.proxy.stats.history.add;

import luj.data.api.use.UseGroup;
import luj.tool.jnproxyan.proxy.database.DatabaseState;
import luj.tool.jnproxyan.proxy.stats.connect.ConnectStats;
import luj.tool.jnproxyan.proxy.stats.history.ConnectHistoryDat;
import luj.tool.jnproxyan.proxy.stats.history.HistoryItem;
import luj.tool.jnproxyan.proxy.util.data.DataBeanCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;

@Component
public class ConnectHistoryAdder {

  public ConnectHistoryAdder inject(ConnectHistoryDat historyDat, DatabaseState dbState, UseGroup using, Long requestId, String targetHost, int targetPort) {
    ConnectHistoryAdder result = new ConnectHistoryAdder();
    result._historyDat = historyDat;
    result._dbState = dbState;
    result._using = using;

    result._requestId = requestId;
    result._targetHost = targetHost;
    result._targetPort = targetPort;

    result._dataMaker = _dataMaker;
    return result;
  }

  public void add() {
    HistoryItem item = _dataMaker.createV2(HistoryItem.class, _using, _dbState);
    item.requestId().set(_requestId);

    item.connectStartTime().set(Instant.now().toEpochMilli());
    item.connectResult().set(HistoryItem.Result.CONNECTING.name());

    item.targetHost().set(_targetHost);
    item.targetPort().set(_targetPort);

    _historyDat.history().put(_requestId, item);
  }

  ConnectHistoryDat _historyDat;
  DatabaseState _dbState;
  UseGroup _using;

  Long _requestId;
  String _targetHost;
  int _targetPort;

  @Autowired
  DataBeanCreator _dataMaker;
}
